/* eslint-disable no-useless-escape */
import { CONFIG } from '@/constants';
import {
    getIdentityCategory,
    getIdentityList,
    getIdentityTransport,
} from '@/servers/api/base';
import {
    register,
    sendCaptcha,
    sendCaptchaEmail,
} from '@/servers/api/userController';
import { getBase64 } from '@/utils';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import {
    LoginForm,
    ProFormCaptcha,
    ProFormCascader,
    ProFormInstance,
    ProFormSelect,
    ProFormText,
    ProFormUploadButton,
} from '@ant-design/pro-components';
import {
    FormattedMessage,
    getLocale,
    setLocale,
    useIntl,
    useModel,
} from '@umijs/max';
import { GetProp, Modal, UploadFile, UploadProps, message, theme } from 'antd';
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react';
const Logo = require('@/assets/logo.png');
type IProps = {
    setnowPage: Dispatch<SetStateAction<string>>;
};
type IIdentity = {
    id: number;
    value: number;
    name: string;
    name_ru: string;
    label: string;
    category_name: string;
    category_name_ru: string;
    is_area: string;
    is_category: string;
    is_industry: string;
    is_product: string;
    is_transport: string;
    country: string;
};
const Register: React.FC<IProps> = (props) => {
    const formRef = useRef<ProFormInstance>();
    const { token } = theme.useToken();
    const { cityOptions } = useModel('global');
    const [identityCategoryList, setidentityCategoryList] = useState([]);
    const [identityTransportList, setidentityTransportList] = useState([]);
    const intl = useIntl();
    const [lang, setlang] = useState(getLocale());
    const regE =
        /(?=^.{3,256}$)^([\w\-]+([\.][\w\-]+)*)@[a-zA-Z0-9][a-zA-Z0-9\-]*[\.][A-Za-z]{2,6}$/;
    const [identityList, setidentityList] = useState([]); //身份下拉信息
    const [identity, setidentity] = useState<IIdentity>(); //当前选中的身份信息
    const onFinish = async (values: any) => {
        let parmas = {
            ...values,
            area_id: values.area_id[values.area_id.length - 1],
            idnum_img:
                values.idnum_img && values.idnum_img[0]?.response.data.url,
        };
        register(parmas)
            .then((res) => {
                localStorage.setItem('token', res.data.token);
                message.success(intl.formatMessage({ id: '注册成功' }));
                props.setnowPage('');
            })
            .catch((err) => {
                message.error(err.msg);
            });
    };
    const toRegister = () => {
        props.setnowPage('');
    };
    function toForget() {
        props.setnowPage('forget');
    }

    async function getCode() {
        const country = formRef?.current?.getFieldValue('country');
        if (country === '0') {
            const mobile = formRef?.current?.getFieldValue('mobile');
            if (!mobile) {
                message.error(intl.formatMessage({ id: '请输入手机号' }));
                throw new Error('获取验证码错误');
            }
            const reg = /^[0-9]{11}$/;
            if (!reg.test(mobile)) {
                message.error(intl.formatMessage({ id: '手机号格式错误' }));
                throw new Error('获取验证码错误');
            }
            await sendCaptcha({
                mobile: mobile,
                event: 'register',
            });
        } else {
            const email = formRef?.current?.getFieldValue('email');
            if (!email) {
                message.error(intl.formatMessage({ id: '请输入邮箱' }));
                throw new Error('请输入邮箱');
            }
            if (!regE.test(email)) {
                message.error(intl.formatMessage({ id: '邮箱格式错误' }));
                throw new Error('邮箱格式错误');
            }
            await sendCaptchaEmail({
                email: email,
                event: 'register',
            });
        }
    }
    function getIdentityListFun() {
        const country = formRef?.current?.getFieldValue('country');
        getIdentityList({
            country: country,
        })
            .then((res) => {
                setidentityList(res.data);
            })
            .catch((err) => {
                console.log('getIdentityList-err', err);
            });
    }
    function countryChange(val: string) {
        setLocale(val === '1' ? 'ru-RU' : 'zh-CN', false);
        setlang(val === '1' ? 'ru-RU' : 'zh-CN');
        getIdentityListFun();
    }
    function getIdentityCategoryFun() {
        getIdentityCategory({
            identity_id: formRef?.current?.getFieldValue('identity_id'),
        }).then((res) => {
            setidentityCategoryList(res.data);
        });
    }
    function getIdentityTransportFun() {
        getIdentityTransport({
            identity_id: formRef?.current?.getFieldValue('identity_id'),
        })
            .then((res) => {
                setidentityTransportList(res.data);
            })
            .catch((err) => {
                console.log('getIdentityTransport-err', err);
            });
    }
    function identityChange(val: number, options: IIdentity | IIdentity[]) {
        if (Array.isArray(options)) return;
        setidentity(options);
        if (options?.is_category === '1') {
            // 获取分类
            getIdentityCategoryFun();
        }
        if (options?.is_transport === '1') {
            // 获取运输方式
            getIdentityTransportFun();
        }
    }
    type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    const handleCancel = () => setPreviewOpen(false);
    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as FileType);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
        setPreviewTitle(
            file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1),
        );
    };
    useEffect(() => {
        getIdentityListFun();
    }, []);
    return (
        <LoginForm
            formRef={formRef}
            onFinish={onFinish}
            // backgroundImageUrl="https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp"
            logo={Logo}
            title="GLUZ"
            contentStyle={{
                background: '#fff',
                padding: '20px',
                borderRadius: '10px',
                width: '500px',
            }}
            containerStyle={{
                // backgroundColor: 'rgba(0, 0, 0,0.65)',
                backdropFilter: 'blur(4px)',
                backgroundImage:
                    'url(https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp)',
                    backgroundSize: 'cover',
            }}
            subTitle={intl.formatMessage({ id: '注册账号' })}
            submitter={{
                searchConfig: {
                    submitText: intl.formatMessage({ id: '注册' }),
                },
            }}
        >
            <ProFormSelect
                name="country"
                fieldProps={{
                    size: 'large',
                }}
                initialValue={lang === 'zh-CN' ? '0' : '1'}
                placeholder={intl.formatMessage({
                    id: '请选择国籍',
                })}
                onChange={countryChange}
                options={[
                    { value: '0', label: intl.formatMessage({ id: '中国' }) },
                    { value: '1', label: intl.formatMessage({ id: '俄罗斯' }) },
                ]}
            />
            <ProFormText
                name="mobile"
                fieldProps={{
                    size: 'large',
                    prefix: (
                        <UserOutlined
                            style={{
                                color: token.colorText,
                            }}
                            className={'prefixIcon'}
                        />
                    ),
                }}
                placeholder={intl.formatMessage({
                    id: '请输入手机号',
                })}
                rules={[
                    {
                        required: true,
                        message: intl.formatMessage({
                            id: '请输入手机号',
                        }),
                    },
                    {
                        pattern: /^[0-9]{11}$/,
                        message: intl.formatMessage({
                            id: '手机号格式错误',
                        }),
                    },
                ]}
            />
            {formRef?.current?.getFieldValue('country') === '1' && (
                <ProFormText
                    name="email"
                    fieldProps={{
                        size: 'large',
                        prefix: (
                            <UserOutlined
                                style={{
                                    color: token.colorText,
                                }}
                                className={'prefixIcon'}
                            />
                        ),
                    }}
                    placeholder={intl.formatMessage({
                        id: '请输入邮箱',
                    })}
                    rules={[
                        {
                            required: true,
                            message: intl.formatMessage({
                                id: '请输入邮箱',
                            }),
                        },
                        {
                            pattern: regE,
                            message: intl.formatMessage({
                                id: '邮箱格式错误',
                            }),
                        },
                    ]}
                />
            )}
            <ProFormText.Password
                name="password"
                fieldProps={{
                    size: 'large',
                    prefix: (
                        <LockOutlined
                            style={{
                                color: token.colorText,
                            }}
                            className={'prefixIcon'}
                        />
                    ),
                }}
                placeholder={intl.formatMessage({
                    id: '请输入密码',
                })}
                rules={[
                    {
                        required: true,
                        message: intl.formatMessage({
                            id: '请输入密码',
                        }),
                    },
                    {
                        pattern: /^.{7,15}$/,
                        message: intl.formatMessage({
                            id: '请设置6-15位密码',
                        }),
                    },
                ]}
            />
            <ProFormText.Password
                name="password_repeat"
                fieldProps={{
                    size: 'large',
                    prefix: (
                        <LockOutlined
                            style={{
                                color: token.colorText,
                            }}
                            className={'prefixIcon'}
                        />
                    ),
                }}
                placeholder={intl.formatMessage({
                    id: '再次确认密码',
                })}
                rules={[
                    {
                        required: true,
                        message: intl.formatMessage({
                            id: '再次确认密码',
                        }),
                    },
                    ({ getFieldValue }) => ({
                        validator(_, value) {
                            if (!value || getFieldValue('password') === value) {
                                return Promise.resolve();
                            }
                            return Promise.reject(
                                new Error(
                                    intl.formatMessage({
                                        id: '两次密码不一致',
                                    }),
                                ),
                            );
                        },
                    }),
                ]}
            />
            <ProFormCaptcha
                fieldProps={{
                    size: 'large',
                    prefix: (
                        <LockOutlined
                            style={{
                                color: token.colorText,
                            }}
                            className={'prefixIcon'}
                        />
                    ),
                }}
                captchaProps={{
                    size: 'large',
                }}
                placeholder={intl.formatMessage({
                    id: '请输入验证码',
                })}
                captchaTextRender={(timing, count) => {
                    if (timing) {
                        return `${count} ${intl.formatMessage({
                            id: '获取验证码',
                        })}`;
                    }
                    return intl.formatMessage({
                        id: '获取验证码',
                    });
                }}
                name="captcha"
                rules={[
                    {
                        required: true,
                        message: intl.formatMessage({
                            id: '请输入验证码',
                        }),
                    },
                ]}
                onGetCaptcha={async () => {
                    await getCode();
                }}
            />
            <ProFormText
                name="username"
                fieldProps={{
                    size: 'large',
                }}
                placeholder={intl.formatMessage({
                    id: '请输入姓名或公司名称',
                })}
                rules={[
                    {
                        required: true,
                        message: intl.formatMessage({
                            id: '请输入姓名或公司名称',
                        }),
                    },
                ]}
            />
            <ProFormSelect
                name="identity_id"
                fieldProps={{
                    size: 'large',
                }}
                onChange={identityChange}
                placeholder={intl.formatMessage({
                    id: '请选择身份',
                })}
                rules={[
                    {
                        required: true,
                        message: intl.formatMessage({
                            id: '请选择身份',
                        }),
                    },
                ]}
                options={identityList}
            />
            {identity?.is_category === '1' && (
                <ProFormSelect
                    name="identity_category_id"
                    fieldProps={{
                        size: 'large',
                    }}
                    placeholder={intl.formatMessage({
                        id: '经营类目主项',
                    })}
                    rules={[
                        {
                            required: true,
                            message: intl.formatMessage({
                                id: '经营类目主项',
                            }),
                        },
                    ]}
                    options={identityCategoryList}
                />
            )}
            {/* 主要产品名称 */}
            {identity?.is_product === '1' && (
                <ProFormText
                    name="product"
                    fieldProps={{
                        size: 'large',
                    }}
                    placeholder={intl.formatMessage({
                        id: '主要产品名称',
                    })}
                    rules={[
                        {
                            required: true,
                            message: intl.formatMessage({
                                id: '主要产品名称',
                            }),
                        },
                    ]}
                />
            )}
            {/* area_id 取最后一个 */}
            {identity?.is_area === '1' && (
                <ProFormCascader
                    name="area_id"
                    fieldProps={{
                        size: 'large',
                        options: cityOptions,
                        // fieldNames: { value: 'label' },
                    }}
                    placeholder={intl.formatMessage({
                        id: '地区',
                    })}
                    rules={[
                        {
                            required: true,
                            message: intl.formatMessage({
                                id: '地区',
                            }),
                        },
                    ]}
                />
            )}
            {/* 运输方式选择 */}
            {identity?.is_transport === '1' && (
                <ProFormSelect
                    name="identity_transport_id"
                    fieldProps={{
                        size: 'large',
                    }}
                    placeholder={intl.formatMessage({
                        id: '运输方式',
                    })}
                    rules={[
                        {
                            required: true,
                            message: intl.formatMessage({
                                id: '运输方式',
                            }),
                        },
                    ]}
                    options={identityTransportList}
                />
            )}
            {/* 从事行业 */}
            {identity?.is_industry === '1' && (
                <ProFormText
                    name="industry"
                    fieldProps={{
                        size: 'large',
                    }}
                    placeholder={intl.formatMessage({
                        id: '主要从事行业',
                    })}
                    rules={[
                        {
                            required: true,
                            message: intl.formatMessage({
                                id: '主要从事行业',
                            }),
                        },
                    ]}
                />
            )}
            {lang === 'ru-Ru' && (
                <>
                    <ProFormUploadButton
                        name="idnum_img"
                        action={CONFIG.HTTP_REQUEST_URL + '/common/upload'}
                        listType="picture-card"
                        title={intl.formatMessage({ id: '身份证图片' })}
                        max={1}
                        fieldProps={{
                            onPreview: handlePreview,
                        }}
                    ></ProFormUploadButton>
                    <Modal
                        open={previewOpen}
                        title={previewTitle}
                        footer={null}
                        onCancel={handleCancel}
                    >
                        <img
                            alt="example"
                            style={{ width: '100%' }}
                            src={previewImage}
                        />
                    </Modal>
                </>
            )}
            <div style={{ marginBlockEnd: 24 }}>
                <a onClick={toRegister}>
                    <FormattedMessage id="登录"></FormattedMessage>
                </a>
                <a style={{ float: 'right' }} onClick={toForget}>
                    <FormattedMessage id="忘记密码"></FormattedMessage>
                </a>
            </div>
        </LoginForm>
    );
};
export default Register;
